package web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;

import entity.Admin;
import entity.Product;
import entity.User;
import enums.travelenums;
import service.User_service;


@Controller
public class User_controller {
	
	private final String LOGIN="login";	
	private final String REGISTER="register";
	private String timeNow=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
	
	@Autowired
	private User_service user_service;
	
	/*普通会员登录*/
	@RequestMapping(value="login",method=RequestMethod.POST)
	public String login(@RequestParam("username") String username,
						@RequestParam("password") String password, Model model,
						HttpServletRequest request){
		
		User user= user_service.getUser(username, password);
		if(user!=null){
			model.addAttribute("succ",user);
			request.getSession().setAttribute("user", user);
			return LOGIN;
		}
		else {
			model.addAttribute("erro","erro");
			return LOGIN;
		}
	}
	
	
	@RequestMapping(value="register",method=RequestMethod.POST)
	public String register(@RequestParam("username") String username,
							@RequestParam("password") String password,
							@RequestParam("repassword") String repassword ,Model model){
		User u= user_service.getUserByName(username);
		if(u==null&&repassword.equals(password)&&username!=""&&password!=""){
			User user=new User(username,password,timeNow,timeNow);
			user_service.saveUser(user);
			model.addAttribute("succ_mes", "succ_mes");
			
			return REGISTER;
		}
		else if(u!=null){
			model.addAttribute("exist", "exist");
			return REGISTER;
		}
		else {
			model.addAttribute("erro_mes", "erro_mes");
			return REGISTER;
		}
	}
	//查询用户名是否存在，和忘记密码时的答案
	@RequestMapping(value="queryname",method=RequestMethod.POST,produces ="text/html;charset=UTF-8")
	@ResponseBody
	public String Queryname(@RequestParam("username")String username,
							@RequestParam(value="answer",required=false)String answer){
		if(username!=null){
			User user=user_service.getUserByName(username);		
			if(user!=null){ 
				if(answer==null){
					return user.getQuestion(); 
				}
				else if(answer.equals(user.getAnswer())){
					return travelenums.SUCCESS.getInfo();
				}
				return travelenums.ERRO.getInfo();
			}
			return travelenums.ERRO.getInfo();	
		}
		return travelenums.ERRO.getInfo();
	}
	
	@RequestMapping(value="querynameAndpw",method=RequestMethod.POST)
	@ResponseBody
	public String QuerynameAndpw(@RequestParam(value="username",required=false)String username,
								@RequestParam("password")String password,HttpSession session){
		if(username==null){
			User user2=(User)session.getAttribute("user");
			if(user2.getPassword().equals(password)){ 
				return travelenums.SUCCESS.getInfo(); }
			else {
				return travelenums.ERRO.getInfo();
			}
		}
		User user=user_service.getUser(username, password);
		if(user!=null)
		{ 	
			return travelenums.SUCCESS.getInfo(); }
		else {
			return travelenums.ERRO.getInfo();
		}
	}
		/*2处更新（未登录时忘记密码，个人中心修改密码）*/
	
	@RequestMapping(value="updateuser",method=RequestMethod.POST)
	@ResponseBody
	public String updateUser(@RequestParam(value="uname",required=false)String username,@RequestParam(value="oldpassword",required=false)String password
							,@RequestParam("newpassword")String newpassword,HttpSession session){
		if(username==null){ 
			User user1=(User)session.getAttribute("user");
			user1.setPassword(newpassword);
			user1.setUpdateTime(timeNow);
			user_service.updateUser(user1);
			return travelenums.SUCCESS.getInfo();
		}
		User user=user_service.getUserByName(username);
		if(user!=null){
			user.setPassword(newpassword);
			user.setUpdateTime(timeNow);
			user_service.updateUser(user);
			return travelenums.SUCCESS.getInfo();
		}
		return travelenums.ERRO.getInfo();
	}
	
	@RequestMapping(value="updateuserphone",method=RequestMethod.POST)
	@ResponseBody
	public String updateUserPhone(@RequestParam(value="phone")String phone,HttpSession session){
		if(phone!=null){
			User user=(User)session.getAttribute("user");
			user.setPhone(phone);;
			user.setUpdateTime(timeNow);
			user_service.updateUser(user);
			return travelenums.SUCCESS.getInfo();
		}
		return travelenums.ERRO.getInfo();
	}
	
	@RequestMapping(value="loginout")
	public String loginout(HttpServletRequest request){
		
		request.getSession().removeAttribute("user");
		return LOGIN;
	}
	
	@RequestMapping(value="user/usercenter/mydata")
	public String PersonData(Model model,HttpServletRequest request){
		User user=(User)request.getSession().getAttribute("user");
		model.addAttribute("user",user);
		
		return "user_center";
	}
	
	@RequestMapping(value="update/user",method=RequestMethod.POST)
	@ResponseBody
	public String updateuser(User user,HttpSession session){
		User u=(User)session.getAttribute("user");
		if(u!=null){
			u.setQuestion(user.getQuestion());
			u.setAnswer(user.getAnswer());
			u.setUpdateTime(timeNow);
			boolean boo=user_service.updateUser(u);
			if(boo){
				System.out.println(boo);
				return travelenums.SUCCESS.getInfo();	
			}
			return travelenums.ERRO.getInfo();
		}
		return travelenums.NOLOGIN.getInfo();
	}
	/*后台*/
	
	@RequestMapping(value="userlist",method=RequestMethod.POST)
	public String userlist(@RequestParam(value="page",defaultValue="1",required=true)Integer page,
							HttpSession session,Model model){
		Admin admin=(Admin)session.getAttribute("admin");
		if(admin!=null){
			Page<User> pa=PageHelper.startPage(page, 8);
			List<User> list=user_service.user_list();
			PageInfo<User> pageinfor=new PageInfo<User>(pa);
			model.addAttribute("page", pageinfor);
			model.addAttribute("userlist", list);

			return "back/user";
		}
		return travelenums.NOLOGIN.getInfo();
	}
	
	/*这里的id指（真正的id（porid，oderid），可以是别的obj，string）前段函数复用的结果*/
	@RequestMapping(value="backsearchuser",method=RequestMethod.POST)
	public String BackSearchProduct(@RequestParam(value="id",required=false)String username,
					@RequestParam(value="page",defaultValue="1",required=true)Integer page,Model model){		
		
		Page<User> pa=PageHelper.startPage(page, 8);
		User user=user_service.getUserByName(username);
		List<User> list=Lists.newArrayList(user);
		PageInfo<User> pageinfor=new PageInfo<User>(pa);
		model.addAttribute("page", pageinfor);
		model.addAttribute("userlist", list);
		return "back/user";
	}
}
